package com.molyfun.parents.service.filedownload;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.util.FileDownloadUtils;
import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.activity.course.bean.CourseMediaBean;
import com.molyfun.parents.activity.course.downloadObserver.CourseDownloadContainer;
import com.molyfun.parents.activity.course.downloadObserver.CourseDownloadProgressCenter;
import com.molyfun.parents.activity.course.view.courseitem.CourseCellFactory;
import com.molyfun.parents.dao.entity.CourseDownloadTask;
import com.molyfun.parents.dao.entity.SingleDownloadTask;
import com.molyfun.parents.dao.gen.CourseDownloadTaskDao;
import com.molyfun.parents.dao.gen.DaoMaster;
import com.molyfun.parents.dao.gen.DaoSession;
import com.molyfun.parents.dao.gen.SingleDownloadTaskDao;
import com.molyfun.parents.rest.QiniuSDK;
import com.molyfun.parents.rest.bean.CourseDetailResponse;
import com.molyfun.parents.utils.Const;
import com.molyfun.parents.utils.GsonUtil;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:12/1/16.
 */
public class CourseDownloadService extends Service {

    public static final String FLAG_COURSE_ID_LIST = "course_list";

    public static final String FLAG_COURSE_DOWNLOAD_MODE = "download_mode";

    public static final String FLAG_MEDIA_LIST = "media_list";

    public static final String FLAG_SINGLE_GAME_ID = "single_game_id";

    public static final String FLAG_SINGLE_GAME_URL = "single_game_url";

    public interface CourseDownloadServiceMode{
        int FLAG_COURSE_DOWNLOAD = 1001;
        int FLAG_MATERIAL_DOWNLOAD = 1002;
        int FLAG_MATERIAL_UPDATE = 1003;
    }

    private int mCurrentDownloadMode = CourseDownloadServiceMode.FLAG_COURSE_DOWNLOAD;

    private CourseDownloadTaskDao courseDownloadTaskDao;
    private SingleDownloadTaskDao singleDownloadTaskDao;

    @Override
    public void onCreate() {
        super.onCreate();
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MFPApplication.getInstance(), Const.DB_NAME, null);
        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        singleDownloadTaskDao = daoSession.getSingleDownloadTaskDao();
        courseDownloadTaskDao = daoSession.getCourseDownloadTaskDao();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (checkBeforeStart(intent)) {
            mCurrentDownloadMode = intent.getIntExtra(FLAG_COURSE_DOWNLOAD_MODE, CourseDownloadServiceMode.FLAG_COURSE_DOWNLOAD);
            if(mCurrentDownloadMode == CourseDownloadServiceMode.FLAG_COURSE_DOWNLOAD){
                ArrayList<String> courseIds = intent.getStringArrayListExtra(FLAG_COURSE_ID_LIST);
                for(String courseId : courseIds){
                    getDownloadInfo(courseId);
                }
            } else if(mCurrentDownloadMode == CourseDownloadServiceMode.FLAG_MATERIAL_DOWNLOAD){

                long[] taskIds = intent.getLongArrayExtra(FLAG_MEDIA_LIST);
                if(taskIds == null || taskIds.length == 0){
                    return super.onStartCommand(intent, flags, startId);
                }
                ArrayList<SingleDownloadTask> tasks = new ArrayList<>();
                for(long taskid : taskIds){
                    SingleDownloadTask singleDownloadTask = singleDownloadTaskDao.queryBuilder().where(SingleDownloadTaskDao.Properties.Id.eq(taskid)).build().unique();
                    tasks.add(singleDownloadTask);
                }

                if(tasks != null && tasks.size() > 0){
                    for(SingleDownloadTask singleDownloadTask : tasks) {
                        downloadSingleTask(singleDownloadTask);
                    }
                }
            }else if(mCurrentDownloadMode == CourseDownloadServiceMode.FLAG_MATERIAL_UPDATE){
                long gameId = intent.getLongExtra(FLAG_SINGLE_GAME_ID, 0l);
                String url = intent.getStringExtra(FLAG_SINGLE_GAME_URL);
                if(gameId != 0l && !TextUtils.isEmpty(url)){
                    List<SingleDownloadTask> singleDownloadTaskList = singleDownloadTaskDao.queryBuilder().where(SingleDownloadTaskDao.Properties.GameId.eq(gameId)).build().list();
                    updateSingleTask(singleDownloadTaskList, url);
                }
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    public boolean checkBeforeStart(Intent intent) {
        if (intent != null) {
            return true;
        }
        return false;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 服务器自动标志为已下载
     */
    private void getDownloadInfo(String courseId){
        Call<CourseDetailResponse> call = MFPApplication.getInstance().getRestClient().getCourseDetail(courseId, Const.TRUE);
        call.enqueue(new Callback<CourseDetailResponse>() {
            @Override
            public void onResponse(Call<CourseDetailResponse> call, Response<CourseDetailResponse> response) {
                if (response.body() != null) {
                    if (response.body().getData() != null) {
                        CourseDetailResponse.CourseDetailBean courseDetailBean = response.body().getData();
                        processCourseBean(courseDetailBean);

                    }
                }
            }

            @Override
            public void onFailure(Call<CourseDetailResponse> call, Throwable t) {

            }
        });
    }

    private void processCourseBean(CourseDetailResponse.CourseDetailBean courseDetailBean){

        CourseDownloadContainer courseDownloadContainer = CourseDownloadProgressCenter.getInstance().handleCourseDownLoadTask(courseDetailBean);
        //保存课程到数据库
        CourseDownloadTask courseDownloadTask = new CourseDownloadTask();
        courseDownloadTask.setDownloadKeyId(courseDetailBean.getDkey());
        courseDownloadTask.setRelid(courseDetailBean.getRelid());
        courseDownloadTask.setJsonStr(GsonUtil.toJson(courseDetailBean));
        courseDownloadTaskDao.insertOrReplace(courseDownloadTask);

        if((courseDetailBean.getMediaobjectlist() != null && courseDetailBean.getMediaobjectlist().size() > 0) || (courseDetailBean.getPlanmediaobjectlist() != null && courseDetailBean.getPlanmediaobjectlist().size() > 0)){

            if(courseDetailBean.getMediaobjectlist() != null ){
                for(CourseMediaBean courseMediaBean : courseDetailBean.getMediaobjectlist()){
//                courseDownloadContainer.addCourse(courseMediaBean);
                    switch (courseMediaBean.getType()){
                        case CourseCellFactory.CourseType.COURSE_IMAGE:
                            downloadImageCourse(courseMediaBean, courseDetailBean.getDkey(), courseDownloadContainer);
                            break;
                        case CourseCellFactory.CourseType.COURSE_MUSIC:
                            downloadMusicCourse(courseMediaBean, courseDetailBean.getDkey(), courseDownloadContainer);
                            break;
                        case CourseCellFactory.CourseType.COURSE_GAME:
                            downloadGameCourse(courseMediaBean, courseDetailBean.getDkey(), courseDownloadContainer);
                            break;
                        case CourseCellFactory.CourseType.COURSE_VIDEO:
                            downloadVideoCourse(courseMediaBean, courseDetailBean.getDkey(), courseDownloadContainer);
                            break;
                    }
                }
            }

            if(courseDetailBean.getPlanmediaobjectlist() != null){
                for(CourseMediaBean courseMediaBean : courseDetailBean.getPlanmediaobjectlist()){
//                courseDownloadContainer.addCourse(courseMediaBean);
                    switch (courseMediaBean.getType()){
                        case CourseCellFactory.CourseType.COURSE_IMAGE:
                            downloadImageCourse(courseMediaBean, courseDetailBean.getDkey(), courseDownloadContainer);
                            break;
                        case CourseCellFactory.CourseType.COURSE_MUSIC:
                            downloadMusicCourse(courseMediaBean, courseDetailBean.getDkey(), courseDownloadContainer);
                            break;
                        case CourseCellFactory.CourseType.COURSE_GAME:
                            downloadGameCourse(courseMediaBean, courseDetailBean.getDkey(), courseDownloadContainer);
                            break;
                        case CourseCellFactory.CourseType.COURSE_VIDEO:
                            downloadVideoCourse(courseMediaBean, courseDetailBean.getDkey(), courseDownloadContainer);
                            break;
                    }
                }
            }


            if( (courseDetailBean.getMediaobjectlist() != null && courseDetailBean.getMediaobjectlist().size() > 0) && !TextUtils.isEmpty(courseDetailBean.getMediaobjectlist().get(0).getUrl())){
                //下载课程封面
                final BaseDownloadTask task = FileDownloader.getImpl().create(courseDetailBean.getMediaobjectlist().get(0).getUrl())
                        .setPath(createPath(courseDetailBean.getMediaobjectlist().get(0).getUrl()))
                        .setCallbackProgressTimes(100);
                task.start();
                //拆分下载

            }else if((courseDetailBean.getPlanmediaobjectlist() != null && courseDetailBean.getPlanmediaobjectlist().size() > 0) && !TextUtils.isEmpty(courseDetailBean.getPlanmediaobjectlist().get(0).getUrl())){
                final BaseDownloadTask task = FileDownloader.getImpl().create(courseDetailBean.getPlanmediaobjectlist().get(0).getUrl())
                        .setPath(createPath(courseDetailBean.getPlanmediaobjectlist().get(0).getUrl()))
                        .setCallbackProgressTimes(100);
                task.start();
            }
        }
    }

    private void updateSingleTask(final List<SingleDownloadTask> singleDownloadTasks,final String url){
        if(!TextUtils.isEmpty(url) && singleDownloadTasks != null && singleDownloadTasks.size() > 0){
            final String fileDownLoadPath = createPath(url);
            final BaseDownloadTask task = FileDownloader.getImpl().create(url)
                    .setPath(fileDownLoadPath)
                    .setCallbackProgressTimes(100)
                    .setListener(new FileDownloadSampleListener() {
                        @Override
                        protected void completed(BaseDownloadTask task) {
                            super.completed(task);
                            for (SingleDownloadTask singleDownloadTask : singleDownloadTasks) {
                                singleDownloadTask.setState(Const.DOWNLOAD_STATE_FINISHED);
                                singleDownloadTask.setPath(fileDownLoadPath);
                                singleDownloadTask.setUrl(url);
                                singleDownloadTaskDao.update(singleDownloadTask);
                            }
                        }
                    });
            task.start();
        }

    }


    private void downloadSingleTask(final SingleDownloadTask singleDownloadTask){
        if(singleDownloadTask != null){
            final BaseDownloadTask task = FileDownloader.getImpl().create(singleDownloadTask.getUrl())
                    .setPath(singleDownloadTask.getPath())
                    .setCallbackProgressTimes(100)
                    .setListener(new FileDownloadSampleListener(){
                        @Override
                        protected void completed(BaseDownloadTask task) {
                            super.completed(task);
                            singleDownloadTask.setState(Const.DOWNLOAD_STATE_FINISHED);
                            singleDownloadTaskDao.update(singleDownloadTask);
                        }
                    });
            task.start();
        }
    }

    private void downloadImageCourse(CourseMediaBean courseMediaBean, String courseDownloadId, CourseDownloadContainer courseDownloadContainer){
        System.out.println("CourseDownloadService--downloadImageCourse-image-url->" + courseMediaBean.getUrl());
        if(!TextUtils.isEmpty(courseMediaBean.getUrl())){
            String fileDownLoadPath = createPath(courseMediaBean.getUrl());
            final BaseDownloadTask task = FileDownloader.getImpl().create(courseMediaBean.getUrl())
                    .setPath(fileDownLoadPath)
                    .setCallbackProgressTimes(100)
                    .setListener(courseDownloadContainer);
            task.start();

            if(checkInsertAvaliable(courseMediaBean.getUrl(), courseDownloadId)){
                SingleDownloadTask singleDownloadTask = new SingleDownloadTask();
                singleDownloadTask.setUrl(courseMediaBean.getUrl());
                singleDownloadTask.setPath(fileDownLoadPath);
                singleDownloadTask.setDownloadKeyId(courseDownloadId);
                singleDownloadTaskDao.insertOrReplace(singleDownloadTask);
            }

        }
    }

    private void downloadMusicCourse(CourseMediaBean courseMediaBean, String courseDownloadId, CourseDownloadContainer courseDownloadContainer){
        System.out.println("CourseDownloadService--downloadImageCourse-music-url->" + courseMediaBean.getUrl());
        if(!TextUtils.isEmpty(courseMediaBean.getUrl())){
            String musicFileDownLoadPath = createPath(courseMediaBean.getUrl());
            final BaseDownloadTask task = FileDownloader.getImpl().create(courseMediaBean.getUrl())
                    .setPath(musicFileDownLoadPath)
                    .setCallbackProgressTimes(100)
                    .setListener(courseDownloadContainer);
            task.start();

            if(checkInsertAvaliable(courseMediaBean.getUrl(), courseDownloadId)){
                SingleDownloadTask singleMusicDownloadTask = new SingleDownloadTask();
                singleMusicDownloadTask.setUrl(courseMediaBean.getUrl());
                singleMusicDownloadTask.setPath(musicFileDownLoadPath);
                singleMusicDownloadTask.setDownloadKeyId(courseDownloadId);
                singleDownloadTaskDao.insertOrReplace(singleMusicDownloadTask);
            }

        }

        if(!TextUtils.isEmpty(courseMediaBean.getImgurl())){
            String coverFileDownLoadPath = createPath(courseMediaBean.getImgurl());
            final BaseDownloadTask coverTask = FileDownloader.getImpl().create(QiniuSDK.getBigUrl(courseMediaBean.getImgurl()))
                    .setPath(coverFileDownLoadPath)
                    .setCallbackProgressTimes(100);
            coverTask.start();

            if(checkInsertAvaliable(courseMediaBean.getImgurl(), courseDownloadId)){
                SingleDownloadTask singleCoverDownloadTask = new SingleDownloadTask();
                singleCoverDownloadTask.setUrl(courseMediaBean.getImgurl());
                singleCoverDownloadTask.setPath(coverFileDownLoadPath);
                singleCoverDownloadTask.setDownloadKeyId(courseDownloadId);
                singleDownloadTaskDao.insertOrReplace(singleCoverDownloadTask);
            }
        }

    }

    private void downloadVideoCourse(CourseMediaBean courseMediaBean, String courseDownloadId, CourseDownloadContainer courseDownloadContainer){
        System.out.println("CourseDownloadService--downloadImageCourse-video-url->" + courseMediaBean.getUrl());
        if(!TextUtils.isEmpty(courseMediaBean.getUrl())){
            String videoFileDownLoadPath = createPath(courseMediaBean.getUrl());
            final BaseDownloadTask task = FileDownloader.getImpl().create(courseMediaBean.getUrl())
                    .setPath(videoFileDownLoadPath)
                    .setCallbackProgressTimes(100)
                    .setListener(courseDownloadContainer);
            task.start();

            if(checkInsertAvaliable(courseMediaBean.getUrl(), courseDownloadId)){
                SingleDownloadTask singleVideoDownloadTask = new SingleDownloadTask();
                singleVideoDownloadTask.setUrl(courseMediaBean.getUrl());
                singleVideoDownloadTask.setPath(videoFileDownLoadPath);
                singleVideoDownloadTask.setDownloadKeyId(courseDownloadId);
                singleDownloadTaskDao.insertOrReplace(singleVideoDownloadTask);
            }

        }

//
//        if(!TextUtils.isEmpty(courseMediaBean.getCover())) {
//            String coverFileDownLoadPath = createPath(courseMediaBean.getCover());
//            final BaseDownloadTask coverTask = FileDownloader.getImpl().create(courseMediaBean.getCover())
//                    .setPath(coverFileDownLoadPath)
//                    .setCallbackProgressTimes(100);
//            coverTask.start();
//            if(checkInsertAvaliable(courseMediaBean.getCover(), courseDownloadId)){
//                SingleDownloadTask singleCoverDownloadTask = new SingleDownloadTask();
//                singleCoverDownloadTask.setUrl(courseMediaBean.getCover());
//                singleCoverDownloadTask.setPath(coverFileDownLoadPath);
//                singleCoverDownloadTask.setDownloadKeyId(courseDownloadId);
//                singleDownloadTaskDao.insertOrReplace(singleCoverDownloadTask);
//            }
//
//        }

    }

    private void downloadGameCourse(CourseMediaBean courseMediaBean, String courseDownloadId, CourseDownloadContainer courseDownloadContainer){
        System.out.println("CourseDownloadService--downloadImageCourse-game-url->" + courseMediaBean.getUrl());
        if(!TextUtils.isEmpty(courseMediaBean.getOfflineurl())){
            String gameZipFileDownLoadPath = createPath(courseMediaBean.getOfflineurl());
            gameZipFileDownLoadPath = gameZipFileDownLoadPath + ".zip";
            final BaseDownloadTask task = FileDownloader.getImpl().create(courseMediaBean.getOfflineurl())
                    .setPath(gameZipFileDownLoadPath)
                    .setCallbackProgressTimes(100)
                    .setListener(courseDownloadContainer);
            task.start();

            if(checkInsertAvaliable(courseMediaBean.getOfflineurl(), courseDownloadId)){
                SingleDownloadTask singleGameDownloadTask = new SingleDownloadTask();
                singleGameDownloadTask.setUrl(courseMediaBean.getUrl());
                singleGameDownloadTask.setPath(gameZipFileDownLoadPath);
                singleGameDownloadTask.setDownloadKeyId(courseDownloadId);
                singleGameDownloadTask.setGameId(courseMediaBean.getGameid());
                singleDownloadTaskDao.insertOrReplace(singleGameDownloadTask);
            }

        }

        if(!TextUtils.isEmpty(courseMediaBean.getImgurl())) {
            String coverFileDownLoadPath = createPath(courseMediaBean.getImgurl());
            final BaseDownloadTask coverTask = FileDownloader.getImpl().create(QiniuSDK.getBigUrl(courseMediaBean.getImgurl()))
                    .setPath(coverFileDownLoadPath)
                    .setCallbackProgressTimes(100);
            coverTask.start();
            if(checkInsertAvaliable(courseMediaBean.getImgurl(), courseDownloadId)){
                SingleDownloadTask singleCoverDownloadTask = new SingleDownloadTask();
                singleCoverDownloadTask.setUrl(courseMediaBean.getImgurl());
                singleCoverDownloadTask.setPath(coverFileDownLoadPath);
                singleCoverDownloadTask.setDownloadKeyId(courseDownloadId);
                singleDownloadTaskDao.insertOrReplace(singleCoverDownloadTask);
            }

        }


    }

    public boolean checkInsertAvaliable(String url, String courseDownloadId){
        List<SingleDownloadTask> singleDownloadTaskList = singleDownloadTaskDao.queryBuilder().where(SingleDownloadTaskDao.Properties.Url.eq(url), SingleDownloadTaskDao.Properties.DownloadKeyId.eq(courseDownloadId)).build().list();
        if(singleDownloadTaskList != null && singleDownloadTaskList.size() > 0) {
            if(singleDownloadTaskList.size() > 1){
                for(int num = 1;  num < singleDownloadTaskList.size(); num++){
                    singleDownloadTaskDao.delete(singleDownloadTaskList.get(num));
                }
            }
            return false;
        }
        return true;
    }

    public String createPath(final String url) {
        if (TextUtils.isEmpty(url)) {
            return null;
        }

        return FileDownloadUtils.getDefaultSaveFilePath(url);
    }

}
